#!/bin/sh
set -e

### BEGIN INIT INFO
# Provides:           dkv-netshare
# Required-Start:     $syslog $remote_fs $network
# Required-Stop:      $syslog $remote_fs $network
# Default-Start:      2 3 4 5
# Default-Stop:       0 1 6
# Short-Description:  Init for docker-volume-netshare
# Description: Docker volume plugin supporting NFS, EFS and CIFS
### END INIT INFO

export PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin

APP="docker-volume-netshare"

# modify these in /etc/default/$APP (/etc/default/dkv-netshare)
DKV_NETSHARE=/usr/bin/$APP
# This is the pid file created/managed by start-stop-daemon
DKV_NETSHARE_SSD_PIDFILE=/var/run/$APP-ssd.pid
DKV_NETSHARE_LOGFILE=/var/log/$APP.log
DKV_NETSHARE_OPTS=
DKV_NETSHARE_DESC="Docker-Volume-Netshare"

# Get lsb functions
. /lib/lsb/init-functions

if [ -f /etc/default/$APP ]; then
	. /etc/default/$APP
fi

# Check docker is present
if [ ! -x $DKV_NETSHARE ]; then
	log_failure_msg "$DKV_NETSHARE not present or not executable"
	exit 1
fi

fail_unless_root() {
	if [ "$(id -u)" != '0' ]; then
		log_failure_msg "$DKV_NETSHARE_DESC must be run as root"
		exit 1
	fi
}

case "$1" in
	start)
		fail_unless_root

		touch "$DKV_NETSHARE_LOGFILE"
		chgrp docker "$DKV_NETSHARE_LOGFILE"


		log_begin_msg "Starting $DKV_NETSHARE_DESC: $APP"
		start-stop-daemon --start --background \
			--no-close \
			--exec "$DKV_NETSHARE" \
			--pidfile "$DKV_NETSHARE_SSD_PIDFILE" \
			--make-pidfile \
			-- \
				$DKV_NETSHARE_OPTS \
					>> "$DKV_NETSHARE_LOGFILE" 2>&1
		log_end_msg $?
		;;

	stop)
		fail_unless_root
		log_begin_msg "Stopping $DKV_NETSHARE_DESC: $APP"
		start-stop-daemon --stop --pidfile "$DKV_NETSHARE_SSD_PIDFILE"
		log_end_msg $?
		;;

	restart)
		fail_unless_root
		dkv_pid=`cat "$DKV_NETSHARE_SSD_PIDFILE" 2>/dev/null`
		[ -n "$dkv_pid" ] \
			&& ps -p $dkv_pid > /dev/null 2>&1 \
			&& $0 stop
		$0 start
		;;

	force-reload)
		fail_unless_root
		$0 restart
		;;

	status)
		status_of_proc -p "$DKV_NETSHARE_SSD_PIDFILE" "$DKV_NETSHARE" "$DKV_NETSHARE_DESC"
		;;

	*)
		echo "Usage: $0 {start|stop|restart|status}"
		exit 1
		;;
esac
